﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace FACUI
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                Application.EnableVisualStyles();
                //ThreadPool.QueueUserWorkItem(new WaitCallback(GetSrc),null);
                Application.SetCompatibleTextRenderingDefault(false);

                //if (BasicClass.CGlobal.IsGetIniFile())
                //{
                //    frmDialog.frmStart _frmStart = new frmDialog.frmStart("Admin");
                //    Application.Run(_frmStart);
                //}
                string strTmp = System.Configuration.ConfigurationManager.AppSettings["dGuPuAvgLevel"].ToString();
                double ret = 0;
                if (double.TryParse(strTmp, out ret))
                {
                    frmDialog.CSource.dAvgLevel = ret;
                }
                BasicClass.CGlobal.StrHostType = System.Configuration.ConfigurationManager.AppSettings["sHostType"].ToString();
                Application.Run(new frmDialog.frmMain());
            }
            catch (Exception ex) 
            {
                System.IO.File.AppendAllText(string.Format("{0}\\{1}.log",Environment.CurrentDirectory,DateTime.Today.Date),ex.ToString());
            }
        }

        private static void GetSrc(object o)
        {
            try
            {
                //接收原始光谱数据 端口8001
                GetSource _udpSource = new GetSource(8001);
                Thread thsource = new Thread(new ThreadStart(_udpSource.ReceiveData));
                thsource.IsBackground = true;
                thsource.Start();
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace+":"+ex.Message ); }
        }
    }
    public class GetSource
    {
        private string strCurPath = string.Empty;
        private string strDirPath = "D:\\";
        private UdpClient _udp = null;
        private IPEndPoint _ipe = null;
        private FileStream _fs = null;
        private string curFileName = string.Empty;
        private DateTime _startTime = DateTime.Now;

        private int _isendPort = 9091;
        private UdpClient _udpSend = null;

        public GetSource(int iRecPort)
        {
            try
            {
                _udp = new UdpClient(iRecPort);
                _ipe = new IPEndPoint(IPAddress.Any, iRecPort);
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
        }

        public void ReceiveData()
        {
            while (true)
            {                
                try
                {
                    byte[] bytes = _udp.Receive(ref _ipe);
                    if (bytes.Length % 512 != 0) continue;
                    SaveBuffer(bytes,_ipe.Address);
                }
                catch (Exception ex){ System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
            }
        }
        
        /// <summary>
        /// 保存原始光谱到文件
        /// </summary>
        /// <param name="bytes"></param>
        private void SaveBuffer(byte[] bytes,IPAddress _ipsend)
        {
            try
            {
                if (curFileName == string.Empty)
                {
                    _startTime = DateTime.Now;
                    curFileName = string.Format("{0}.dat", _startTime.ToString("yyyyMMddHHmmss"));
                }
                if (_startTime.AddMinutes(30) <= DateTime.Now)
                {
                    _startTime = DateTime.Now;
                    curFileName = string.Format("{0}.dat", _startTime.ToString("yyyyMMddHHmmss"));
                }
                if (!File.Exists(strDirPath + "\\" + curFileName))
                {
                    if (_fs != null)
                    {
                        string strInx = _fs.Name;
                        _fs.Close();
                        _fs.Dispose();
                        _fs = null;
                    }
                    _fs = File.OpenWrite(strDirPath + "\\" + curFileName);
                }
                if (_fs == null)
                {
                    _fs = File.OpenWrite(strDirPath + "\\" + curFileName);
                    strCurPath = _fs.Name;
                }
                _fs.Write(bytes, 0, bytes.Length);
                _fs.Flush();
                //转发数据
                SendBuffer(bytes, _ipsend);
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace + ":" + ex.Message); }
        }

        private void SendBuffer(byte[] bytes,IPAddress ipAddr)
        {
            try
            {
                if (_udpSend == null)
                {
                    _udpSend = new UdpClient();
                    _udpSend.Connect(ipAddr, _isendPort);
                }
                _udpSend.Send(bytes, bytes.Length);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace+":"+ex.Message );
            }
        }

    }
}

